package model;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import sun.security.pkcs.PKCS10;
import sun.security.x509.X500Name;

public class CSRGenerator {

	private CSR csr;

	public CSRGenerator(CSR csr) {
		this.csr = csr;
	}

	public PKCS10 generatePKCS10() {

		// init new PKSC10
		PKCS10 pkcs10 = new PKCS10(this.csr.getPublickey());

		// sign
		this.csr.initSignature();

		try {
			X500Name x500Name = new X500Name(this.csr.getCommonName(),
					this.csr.getOrganizationalUnit(),
					this.csr.getOrganization(), this.csr.getLocality(),
					this.csr.getState(), this.csr.getCountry());
			pkcs10.encodeAndSign(x500Name, this.csr.getSignature());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return pkcs10;
	}

	public String toString(PKCS10 pkcs10) {

		ByteArrayOutputStream bs = new ByteArrayOutputStream();
		PrintStream ps = new PrintStream(bs);

		try {
			pkcs10.print(ps);
		} catch (Exception e) {
			e.printStackTrace();
		}

		byte[] c = bs.toByteArray();
		try {
			if (ps != null)
				ps.close();
			if (bs != null)
				bs.close();
		} catch (Throwable th) {
		}
		return new String(c);
	}
}
